package com.example.demo.test;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

/**
 * @Description TODO
 * @Author wzh
 * @Date 2022/6/14 8:52 下午
 * @Version 1.0
 */
public class Lc102 {
    public static void main(String[] args) {
        TreeNode treeNode9 = new TreeNode(9,null,null);
        TreeNode treeNode3 = new TreeNode(15);
        TreeNode treeNode6 = new TreeNode(7);
        TreeNode treeNode20 = new TreeNode(20,treeNode3,treeNode6);
        TreeNode treeNode5 = new TreeNode(3,treeNode9,treeNode20);
        System.out.println(bfs(treeNode5));
    }


    public static List<List<Integer>> bfs(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> level = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll(); // Java 的 pop 写作 poll()
                level.add(node.val);
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            res.add(level);
        }
        return res;
    }


}
